package com.vhdadw.component;

import com.vhdadw.config.SmsConfig;
import com.vhdadw.utils.CommonUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@Slf4j
public class SmsComponent {

    private static final String URL_TEMPLATE = "https://gyytz.market.alicloudapi.com/sms/smsSend?mobile=%s&templateId=%s&smsSignId=%s&param=%s";

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送短信
     *
     * @param to
     * @param templateId
     * @param smsSignId
     * @param param
     */
    @Async("threadPoolTaskExecutor")
    public void send(String to, String templateId, String smsSignId, String param) {

        long beginTime = CommonUtil.getCurrentTimestamp();

        String url = String.format(URL_TEMPLATE, to, templateId, smsSignId, param);
        System.out.println(url);
        HttpHeaders headers = new HttpHeaders();
        // 请求头
        headers.set("Authorization", "APPCODE " + smsConfig.getAppCode());
        HttpEntity entity = new HttpEntity<>(headers);
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);

        long endTime = CommonUtil.getCurrentTimestamp();

        log.info("耗时={},url={},body={}", endTime-beginTime, url, response.getBody());
        if (response.getStatusCode() == HttpStatus.OK) {
            log.info("发送短信验证码成功");
        } else {
            log.error("发送短信验证码失败：{}", response.getBody());
        }
    }


    @Autowired
    private SmsConfig smsConfig;
}
